package com.rtz.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassDescription XXX
 * @author ksflying
 * @date 2019年2月27日 下午3:39:55
 * 
 */
public class RSA {

	public static final String KEY_ALGORITHM = "RSA";
	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	private static final String PUBLIC_KEY = "RSAPublicKey";
	private static final String PRIVATE_KEY = "RSAPrivateKey";
	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;
	// 获得公钥字符串
	public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
		// 获得map中的公钥对象 转为key对象
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		// 编码返回字符串
		return encryptBASE64(key.getEncoded());
	}

	// 获得私钥字符串
	public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
		// 获得map中的私钥对象 转为key对象
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		// 编码返回字符串
		return encryptBASE64(key.getEncoded());
	}

	// 获取公钥
	public static PublicKey getPublicKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	// 获取私钥
	public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	// 解码返回byte
	public static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	// 编码返回字符串
	public static String encryptBASE64(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	// ***************************签名和验证*******************************
	public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
		PrivateKey priK = getPrivateKey(privateKeyStr);
		Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
		sig.initSign(priK);
		sig.update(data);
		return sig.sign();
	}

	public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
		PublicKey pubK = getPublicKey(publicKeyStr);
		Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
		sig.initVerify(pubK);
		sig.update(data);
		return sig.verify(sign);
	}

	// ************************加密解密**************************
	public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
		PublicKey publicKey = getPublicKey(publicKeyStr);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = plainText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		int i = 0;
		byte[] cache;
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptText = out.toByteArray();
		out.close();
		return encryptText;
	}

	public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
		PrivateKey privateKey = getPrivateKey(privateKeyStr);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int inputLen = encryptText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] plainText = out.toByteArray();
		out.close();
		return plainText;
	}

	public static Map<String, Object> initKey() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		keyPairGen.initialize(1024);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> keyMap = new HashMap<String, Object>(2);
		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);
		return keyMap;
	}
	/**
	 * 加密
	 * 
	 * @param encryptionString
	 * @param publicKey
	 * @return
	 * @throws Exception
	 */
	public static String encryption(String encryptionString, String publicKey) throws Exception {
		byte[] cipherText;
		cipherText = encrypt(encryptionString.getBytes(), publicKey);
		// 加密后的东西
		return Base64.encode(cipherText);
	}
	/**
	 * 解密
	 * 
	 * @param decryptString
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String decryptString, String privateKey) throws Exception {

		byte[] plainText = decrypt(Base64.decode(decryptString), privateKey);
		return new String(plainText);
	}

	/**
	 * 验证数据是否被篡改
	 * 
	 * @param verifyString
	 * @param privateKey
	 * @param publicKey
	 * @return
	 */
	public static boolean verify(String verifyString, String privateKey, String publicKey) {
		System.out.println("原文:" + verifyString);
		byte[] signature;
		try {
			signature = sign(verifyString.getBytes(), privateKey);
			boolean status = verify(verifyString.getBytes(), signature, publicKey);
			return status;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;

	}

	public static void main(String[] args) {
		try {
			String string1 = encryption("Hello World!", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWuWqwgqBelnvbz67ajt5JjxRFcdQxr2g+Y6fLfwTF0cmj6i6ygnBSRQBiwLcqOsuzsP4DASQYWvTXfpExATuj8GoCENKDUXbryQcd6ArEeATjbl2z9Nfgq08hZnxWK4/5Qd4DgvzMeBvVMCvL+3X9MiLCOReq6ORTPYBnK+TgGQIDAQAB");
			System.err.println("加密后的Base64:"+string1);
			String string2 = decrypt(string1, "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJa5arCCoF6We9vPrtqO3kmPFEVx1DGvaD5jp8t/BMXRyaPqLrKCcFJFAGLAtyo6y7Ow/gMBJBha9Nd+kTEBO6PwagIQ0oNRduvJBx3oCsR4BONuXbP01+CrTyFmfFYrj/lB3gOC/Mx4G9UwK8v7df0yIsI5F6ro5FM9gGcr5OAZAgMBAAECgYBjX6I4+BbV5i+JUFd/X9ys8Pmzg4YcsAJxx/CUWY2DA3sHaFobdaaqhzXm5hqdbCBru9DtmC39JNLy1U7S2XZA8ABnResBMuuvIdXVMRQEarS9JunyKi4+JMc+HHtVhYn2Fsm6SfQ4VRMZ/oZZQ7VVewUyie8VpcojLO0ncvneVQJBAMyOmus5tfE92lvkO8/NdWFJkOMoNDdNi1KauYLxHk6W1d6aYqYxTWkV3SqeL+BO2PobsuUZHPue9OyKF0VTla8CQQC8oQ4PsRAr2W5vWjClD+9JxaNe2CSlwx0b9OEDzpsLE4dtervEtUDahaVBhttdGNseL5xvilyg03FXDoSnQSC3AkBSF4Tqk72FtDn2mNC8I4tQ4NIpp4/VBeS84OVEPHnaNkRcUn72jWCwpJqeqN8z2NDRBt6zfHGaNX+7keum4dV3AkAt0u5oj3o/PM4gTQe+QbW+9T1wABA/GLxMm1vCogF2WmMvDH7rFaFQtODln05ROoWYurZFPpasF1HUdVlyjFbXAkBhbbQouLNCXNWh6FfULYSzJB31Hzg9vv3f+pRo6CLaEjYZu76ZI21mz1WtqeRQZM40LSnzJTbnR1zoo7oF7mG9");
			System.err.println("解密后的原文:"+string2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//tets1();
	}
	/**
	 * 系统生成公钥私钥
	 */
	public static void tets2() {
		Map<String, Object> keyMap;
		byte[] cipherText;
		String input = "Hello World!";
		try {
			keyMap = initKey();
			String publicKey = getPublicKeyStr(keyMap);
			System.out.println("公钥------------------");
			System.out.println(publicKey);
			String privateKey = getPrivateKeyStr(keyMap);
			System.out.println("私钥------------------");
			System.out.println(privateKey);

			System.out.println("测试可行性-------------------");
			System.out.println("明文=======" + input);

			cipherText = encrypt(input.getBytes(), publicKey);
			// 加密后的东西
			System.out.println("密文=======" + new String(cipherText));
			// 开始解密
			byte[] plainText = decrypt(cipherText, privateKey);
			System.out.println("解密后明文===== " + new String(plainText));
			System.out.println("验证签名-----------");

			String str = "被签名的内容";
			System.out.println("\n原文:" + str);
			byte[] signature = sign(str.getBytes(), privateKey);
			boolean status = verify(str.getBytes(), signature, publicKey);
			System.out.println("验证情况：" + status);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void tets1() {

		byte[] cipherText;
		String input = "Hello World!";
		try {
			String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWuWqwgqBelnvbz67ajt5JjxRFcdQxr2g+Y6fLfwTF0cmj6i6ygnBSRQBiwLcqOsuzsP4DASQYWvTXfpExATuj8GoCENKDUXbryQcd6ArEeATjbl2z9Nfgq08hZnxWK4/5Qd4DgvzMeBvVMCvL+3X9MiLCOReq6ORTPYBnK+TgGQIDAQAB";
			System.out.println("公钥------------------");
			System.out.println(publicKey);
			String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJa5arCCoF6We9vPrtqO3kmPFEVx1DGvaD5jp8t/BMXRyaPqLrKCcFJFAGLAtyo6y7Ow/gMBJBha9Nd+kTEBO6PwagIQ0oNRduvJBx3oCsR4BONuXbP01+CrTyFmfFYrj/lB3gOC/Mx4G9UwK8v7df0yIsI5F6ro5FM9gGcr5OAZAgMBAAECgYBjX6I4+BbV5i+JUFd/X9ys8Pmzg4YcsAJxx/CUWY2DA3sHaFobdaaqhzXm5hqdbCBru9DtmC39JNLy1U7S2XZA8ABnResBMuuvIdXVMRQEarS9JunyKi4+JMc+HHtVhYn2Fsm6SfQ4VRMZ/oZZQ7VVewUyie8VpcojLO0ncvneVQJBAMyOmus5tfE92lvkO8/NdWFJkOMoNDdNi1KauYLxHk6W1d6aYqYxTWkV3SqeL+BO2PobsuUZHPue9OyKF0VTla8CQQC8oQ4PsRAr2W5vWjClD+9JxaNe2CSlwx0b9OEDzpsLE4dtervEtUDahaVBhttdGNseL5xvilyg03FXDoSnQSC3AkBSF4Tqk72FtDn2mNC8I4tQ4NIpp4/VBeS84OVEPHnaNkRcUn72jWCwpJqeqN8z2NDRBt6zfHGaNX+7keum4dV3AkAt0u5oj3o/PM4gTQe+QbW+9T1wABA/GLxMm1vCogF2WmMvDH7rFaFQtODln05ROoWYurZFPpasF1HUdVlyjFbXAkBhbbQouLNCXNWh6FfULYSzJB31Hzg9vv3f+pRo6CLaEjYZu76ZI21mz1WtqeRQZM40LSnzJTbnR1zoo7oF7mG9";
			System.out.println("私钥------------------");
			System.out.println(privateKey);

			System.out.println("测试可行性-------------------");
			System.out.println("明文=======" + input);

			cipherText = encrypt(input.getBytes(), publicKey);
			// 加密后的东西
			System.out.println("密文=======" + new String(cipherText));
			// 开始解密
			byte[] plainText = decrypt(cipherText, privateKey);
			System.out.println("解密后明文===== " + new String(plainText));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
